<?php

/**
 * @Author: 网名
 * @Date:   2018-06-07 22:01:17
 * @Last Modified by:   网名
 * @Last Modified time: 2018-06-07 22:02:56
 */

/**
* 打包业务
*/
namespace app\index\controller;
use app\common\logic\GoodsLogic;
use app\index\model\PackModel;
use think\Db;
class Pack extends Base
{
    public function _initialize() 
    {   
        $this->user = array();
        $this->user_id = 0;
         parent::_initialize();
         if(session('?user'))
        {
            $session_user = session('user');
            $user = db('users')->where("user_id", $session_user['user_id'])->find();
            session('user',$user);  //覆盖session 中的 user     
            $this->user = $user;
            $this->user_id = $user['user_id']; 
        }else{
            $nologin = array();
            if(!in_array(ACTION_NAME,$nologin)){
                $this->redirect('Index/User/login');
                exit;
            }
        }
        $this->assign('user',$this->user); //存储用户信息
        $this->assign('user_id',$this->user_id);     
    }
	
	//打包业务
    public function packlist(){
        $fromList = config('platform');
        if(IS_POST) {
            $param = input('post.');
            $param['user_id'] = $this->user_id;
            
            $pack = new PackModel();
            $row = $pack->getPackByWhere($param);
            $list = collection($row)->toArray();
            $packStatus = config('PACK_STATUS');
            $payStatus = config('PAY_STATUS');
            foreach ($list as $key => $value) {
                $list[$key]['pack_status_name'] = $packStatus[$value['pack_status']];
                $list[$key]['pay_status_name'] = $payStatus[$value['pay_status']];
                $list[$key]['pack_file'] = $value['pack_file'];
                $list[$key]['platform_code'] = $fromList[$value['platform_code']]['name'];
            }
            $count = $pack->getPackCount($param);
            $return = ['data'=>$list,'code'=>0,'count'=>$count,'msg'=>""];    
             $this->ajaxReturn($return);    
        }
        $this->assign('fromList',$fromList);
        return $this->fetch();
    }
	
	//完成余额扣款
	public function applyPay(){
		$pack_id = input('pack_id/d',0);
		$packInfo = db('pack')->where(['pack_id'=>$pack_id])->find();
        $platform = config('platform');
        $free = $platform[$packInfo['platform_code']]['free'];
		if($packInfo['pay_status']==1){
			$this->ajaxReturn(['status'=>0,'msg'=>'请勿重复支付']);
		}
		//检测用户余额是否充足
		$user_money = db('users')->where(['user_id'=>$this->user_id])->getField('user_money');
		if ($user_money<$free) {
			 $this->ajaxReturn(['status'=>0,'msg'=>'余额不足请充值','url'=>url('User/recharge')]);
		}
		try{
			db('pack')->where(['pack_id'=>$pack_id])->save(['pay_status'=>1,'pack_status'=>1]);
		}catch(\Exception $e){
			$this->ajaxReturn(['status'=>0,'msg'=>$e->getMessage()]);
		}
		accountLog($this->user_id, -$free,0, '打包业务',0,0 ,'');
		$this->ajaxReturn(['status'=>1,'msg'=>'已从您的余额扣款成功']);
		
	}

    //批量支付
    public function batchPay(){
    
        $param = input('post.');
        $fromList = config('platform');
        foreach ($param['data'] as $key => $value) {
            if (db('pack')->where(['pack_id'=>$value['pack_id'],'pay_status'=>1])->count()) {
                $this->ajaxReturn(['status'=>0,'msg'=>'所选记录中存在已支付记录,请选择未支付记录']);
            }
            $packids[] = $value['pack_id'];

        }



        if ($packids) {
            $free = 0;
            foreach ($packids as $key => $value) {
                $platform_code = db('pack')->where(['pack_id'=>$value])->getField('platform_code');
                $free = $free + $fromList[$platform_code]['free'];
            }
            //检测用户余额是否充足
            $user_money = db('users')->where(['user_id'=>$this->user_id])->getField('user_money');
            if ($user_money<$free) {
                 $this->ajaxReturn(['status'=>0,'msg'=>'余额不足请充值','url'=>url('User/recharge')]);
            }
            Db::startTrans();
            try {
                db('pack')->where('pack_id','in',implode(',', $packids))->setField(['pay_status'=>1,'pack_status'=>1]);
                accountLog($this->user_id, -$free,0, '打包业务'.count($packids).'单',0,0 ,'');
                // 提交事务
                Db::commit();
                $this->ajaxReturn(['status'=>1,'msg'=>'批量支付成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->ajaxReturn(['status'=>0,'msg'=>$e->getMessage()]);
            }
            
        }


        
    }

    //商品列表
    public function goodslist(){
        $where = ['user_id'=>$this->user_id];
        if(IS_POST) {
            $page = input('page',1);
            $limit = input('limit',10); //显示记录数
            $express = config('Express');
            $row = db('goods')->where($where)->limit($page,$limit)->order('goods_id desc')->select();
            foreach ($row as $key => $value) {
                $row[$key]['express_code'] = $express[$value['express_code']]."(".$value['express_code'].")";
                
            }
            $count = db('goods')->where($where)->count();
            $return = ['data'=>$row,'code'=>0,'count'=>$count,'msg'=>""];    
             $this->ajaxReturn($return);    
        }
        return $this->fetch();
    }

    public function packadd(){
        if (IS_POST) {
            $platform = config('platform');
            $time = time();
            $data = input('post.');
            cookie('inputData',json_encode($data));//保存本地发布草稿
            
            $validate = new \app\index\validate\Pack;
            $result = $validate->check($data);
            if(!$result){
                $this->error($validate->getError());
            }
            if (db('pack')->where('pack_status','neq',5)->where(['pack_number'=>$data['pack_number']])->count()) {
                $this->error('该面单已存在，请联系管理员');exit;
            }

            //检测用户余额是否充足
            $user_money = db('users')->where(['user_id'=>$this->user_id])->getField('user_money');
            $free = $platform[$data['platform_code']]['free'];
            if ($user_money<$free) {
                 $this->error('余额不足请充值',url('User/recharge'));exit;
            }

            $data['user_id'] = $this->user_id;
            $data['create_time'] = $time;
            $data['free'] = $free;

            $pack = new PackModel;
            $result = $pack->insertPack($data);
            if ($result['status']==0) {
                $this->error($result['msg']);
            }
            cookie('inputData',null);//用户提交订单成功后清理编辑 记录
            $this->success($result['msg'],url('Pack/packlist'));
            
            
            
            
        }

        $platform = config('platform');

        $info = json_decode(cookie('inputData'),1);

        if (isset($info)) {
            foreach ($info['goods_name'] as $key => $value) {
                $info['goodsList'][$key]['goods_name'] = $value;
            }
            foreach ($info['goods_num'] as $key => $value) {
                $info['goodsList'][$key]['goods_num'] = $value;
            }
            foreach ($info['goods_origin'] as $key => $value) {
                $info['goodsList'][$key]['goods_origin'] = $value;
            }
            foreach ($info['express_code'] as $key => $value) {
                $info['goodsList'][$key]['express_code'] = $value;
            }
            foreach ($info['express_number'] as $key => $value) {
                $info['goodsList'][$key]['express_number'] = $value;
            }
        }
        
        $Express = config('Express');
    	$this->assign('Express',$Express);
        $this->assign('info',$info);
        $this->assign('platform',$platform);
        return $this->fetch();
    }

    //取消面单
    public function packCancel()
    {
        $where['pack_id'] = input('pack_id/d');
        db('pack')->where($where)->update(['update_time'=>time(),'pack_status'=>5]);//标记为作废
        $return = ['data'=>'','code'=>0,'msg'=>"操作成功"];    
         $this->ajaxReturn($return);    
    }

    public function packinfo(){
        $id = input('id/d',0);
        $pack = new PackModel;
        $info = $pack->getPackInfo($id);
        $status = config('GOODS_STATUS');
		$Express = config('Express');
        $this->assign('info',$info);
        $this->assign('status',$status);
        $this->assign('Express',$Express);
        return $this->fetch();
    }



    //查询快递公司编码
    public function get_company_code(){
    	$Express = config('Express');
    	$this->assign('Express',$Express);
        return $this->fetch();
    }

 

	
}